package com.mxx.common.data.domain;


import com.mxx.common.tool.SnowflakeIdWorker;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;

import java.io.Serializable;
import java.util.Properties;

public class SnowflakeStringIdGenerate implements IdentifierGenerator, Configurable {


    private SnowflakeIdWorker snowflakeIdWorker;


    public SnowflakeStringIdGenerate() {
        this.snowflakeIdWorker = new SnowflakeIdWorker(1L, 1L);
    }

    @Override
    public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {

    }

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        if (JpaThreadContext.hasId()) {
            Serializable id = JpaThreadContext.getUserId();
            JpaThreadContext.removeId();
            return id;
        }
        return Long.toString(snowflakeIdWorker.nextId());
    }

}
